package com.yrd.common.handler;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class Handler {
	Looper looper;
	public Handler(Looper looper) {
		this.looper = looper;
	}
	
	public Message obtainMessage(){
		Message message = new Message();
		message.setHandle(this);
		return message;
	}
	
	public void sendMessage(Message message){
		sendMessage(message,0);
	}
	
	public void sendMessage(Message message,long delay){
		message.type= Message.TYPE_MESSAGE;
		looper.queue.add(message, System.currentTimeMillis()+delay);
	}
	public void remove(Message message){
		looper.queue.remove(this, message, Message.TYPE_MESSAGE);
	}
	
	public void post(Runnable runnable){
		post(runnable,0);
	}
	public void post(Runnable runnable,long delay){
		Message message = new Message();
		message.setHandle(this);
		message.type= Message.TYPE_RUNNABLE;
		message.runnable = runnable;
		looper.queue.add(message, System.currentTimeMillis()+delay);
	}
	public void remove(Runnable runnable){
		looper.queue.remove(this, runnable, Message.TYPE_RUNNABLE);
	}
	
	public<T> Future<T> post(Callable<T> callable){
		return post(callable,0);
	}
	public<T> Future<T> post(Callable<T> callable,long delay){
		Message message = new Message();
		message.setHandle(this);
		message.type= Message.TYPE_CALLABLE;
		message.callable = callable;
		message.future = new FutureTask<T>(callable);
		looper.queue.add(message, System.currentTimeMillis()+delay);
		return (Future<T>) message.future;
	}
	public<T> void remove(Callable<T> callable){
		looper.queue.remove(this, callable, Message.TYPE_CALLABLE);
	}
	
	
	public void handleMessage(Message message){
		
	}
	
	
}
